package com.bookstore.back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bookstore.back.entity.UserFavorite;
import com.bookstore.back.mapper.UserFavoriteMapper;
import com.bookstore.back.service.UserFavoriteService;
import com.bookstore.back.util.UserContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 用户收藏服务实现类
 * 
 * @author 程序猿_Ti
 * @since 2025-07-22
 */
@Slf4j
@Service
public class UserFavoriteServiceImpl extends ServiceImpl<UserFavoriteMapper, UserFavorite> implements UserFavoriteService {

    @Autowired
    private UserFavoriteMapper userFavoriteMapper;

    @Autowired
    private UserContextUtil userContextUtil;

    @Override
    @Transactional
    public boolean addFavorite(Integer bookId) {
        try {
            // 获取当前用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("用户未登录");
            }

            // 检查是否已收藏
            if (isFavorite(bookId)) {
                throw new RuntimeException("该图书已在收藏夹中");
            }

            // 创建收藏记录
            UserFavorite favorite = new UserFavorite();
            favorite.setUserId(currentUserId.intValue());
            favorite.setBookId(bookId);
            favorite.setCreatedAt(LocalDateTime.now());

            return this.save(favorite);
        } catch (Exception e) {
            log.error("添加收藏失败：{}", e.getMessage());
            throw new RuntimeException("添加收藏失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public boolean removeFavorite(Integer bookId) {
        try {
            // 获取当前用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("用户未登录");
            }

            // 删除收藏记录
            QueryWrapper<UserFavorite> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", currentUserId.intValue())
                       .eq("book_id", bookId);

            return this.remove(queryWrapper);
        } catch (Exception e) {
            log.error("取消收藏失败：{}", e.getMessage());
            throw new RuntimeException("取消收藏失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public boolean toggleFavorite(Integer bookId) {
        try {
            if (isFavorite(bookId)) {
                removeFavorite(bookId);
                return false; // 取消收藏
            } else {
                addFavorite(bookId);
                return true; // 添加收藏
            }
        } catch (Exception e) {
            log.error("切换收藏状态失败：{}", e.getMessage());
            throw new RuntimeException("操作失败：" + e.getMessage());
        }
    }

    @Override
    public boolean isFavorite(Integer bookId) {
        try {
            // 获取当前用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                return false;
            }

            return userFavoriteMapper.checkUserFavorite(currentUserId.intValue(), bookId) > 0;
        } catch (Exception e) {
            log.error("检查收藏状态失败：{}", e.getMessage());
            return false;
        }
    }

    @Override
    public List<Map<String, Object>> getUserFavoriteList() {
        try {
            // 获取当前用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("用户未登录");
            }

            return userFavoriteMapper.getUserFavoriteList(currentUserId.intValue());
        } catch (Exception e) {
            log.error("获取收藏列表失败：{}", e.getMessage());
            throw new RuntimeException("获取收藏列表失败：" + e.getMessage());
        }
    }

    @Override
    public IPage<Map<String, Object>> getUserFavoriteListPage(Map<String, Object> params) {
        try {
            // 获取当前用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("用户未登录");
            }

            // 分页参数
            int current = Integer.parseInt(params.getOrDefault("current", "1").toString());
            int size = Integer.parseInt(params.getOrDefault("size", "10").toString());

            Page<Map<String, Object>> page = new Page<>(current, size);
            return userFavoriteMapper.getUserFavoriteListPage(page, currentUserId.intValue());
        } catch (Exception e) {
            log.error("获取收藏列表失败：{}", e.getMessage());
            throw new RuntimeException("获取收藏列表失败：" + e.getMessage());
        }
    }

    @Override
    public int getUserFavoriteCount() {
        try {
            // 获取当前用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                return 0;
            }

            return userFavoriteMapper.getUserFavoriteCount(currentUserId.intValue());
        } catch (Exception e) {
            log.error("获取收藏数量失败：{}", e.getMessage());
            return 0;
        }
    }

    @Override
    @Transactional
    public boolean clearUserFavorites() {
        try {
            // 获取当前用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("用户未登录");
            }

            // 删除用户所有收藏
            QueryWrapper<UserFavorite> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", currentUserId.intValue());

            return this.remove(queryWrapper);
        } catch (Exception e) {
            log.error("清空收藏失败：{}", e.getMessage());
            throw new RuntimeException("清空收藏失败：" + e.getMessage());
        }
    }
}
